package com.smarthome.web.property.controller.account;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.smarthome.domain.enums.AccountStatus;
import com.smarthome.common.tools.SHACipher;
import com.smarthome.core.account.AccountService;
import com.smarthome.domain.bean.ShAccount;
import com.smarthome.domain.bean.ShResidence;
import com.smarthome.domain.bean.ShUser;
import com.smarthome.domain.common.Result;
import com.smarthome.domain.vo.boss.Combobox;
import com.smarthome.domain.vo.boss.DataGrid;
import com.smarthome.domain.vo.boss.PageHelper;
import com.smarthome.web.property.utils.UserHolder;

/**
* @author zyf
* @date 2015年9月15日 下午6:30:50
* @version 1.0
* @Description: 业主管理类
 */
@Controller
@RequestMapping(value="/account")
public class AccountController {
	
	@Resource
	private AccountService accountService;
	
	@RequestMapping("/views")
	public String views(HttpServletRequest request){
		//设置权限
		setAuth(request);
		
		return "/account/account";
	}
	
	@RequestMapping("/dataGrid")
	@ResponseBody
	public DataGrid dataGrid(ShAccount account,PageHelper page){
		if(!UserHolder.isSuperResidence()){
			account.setResidenceId(UserHolder.getCurrentResidenceId());
		}
		if(account.getStatus()==null){//默认查询正常用户
			account.setStatus(AccountStatus.NORMAL.getType());
		}
		
		return accountService.queryDataGrid(account, page);
	}
	
	
	@RequestMapping("/addPage")
	public String addPage(){
		return "/account/accountAdd";
	}
	
	@RequestMapping("/add")
	@ResponseBody
	public Result add(ShAccount account,HttpServletRequest request,MultipartFile head){
		Result res = null;
		if(accountService.longinNameExist(account.getLoginName())){
			res=Result.failure("登录名已存在!");
		}else{
			try {
				account.setLoginPwd(SHACipher.encrypt(account.getLoginPwd()));
			} catch (Exception e) {
				e.printStackTrace();
			}
			account.setStatus(AccountStatus.NORMAL.getType());
			//保存头像
			saveFile(request, account,head);
			accountService.add(account);
			res = Result.success("添加业主信息成功！");
		}
		
		return res;
	}
	
	@RequestMapping("/editPage")
	public String editPage(HttpServletRequest request,Long id){
		ShAccount account=accountService.queryAccountById(id);
		request.setAttribute("account", account);
		
		return "/account/accountEdit";
	}
	
	@RequestMapping("/edit")
	@ResponseBody
	public Result edit(HttpServletRequest request,ShAccount account,MultipartFile head){
		Result res=null;
		ShAccount last=accountService.queryAccountById(account.getId());
		if(!last.getLoginName().equals(account.getLoginName())&&accountService.longinNameExist(account.getLoginName())){
			res=Result.failure("登录名重复，请重新输入！");
		}else{
			//保存头像
			saveFile(request, account,head);
			accountService.edit(account);
			res = Result.success("更改业主信息成功！");
		}
		return res;
	}
	
	/**
	 * @return
	 */
	@RequestMapping("/editHousePage")
	public String editHosePage(HttpServletRequest request,Long id){
		ShAccount account=accountService.queryAccountById(id);
		request.setAttribute("account", account);
		setAuth(request);
		return "/account/accountEditHouse";
	}
	
	@RequestMapping("/delete")
	@ResponseBody
	public Result delete(Long id){
		accountService.delete(id);
		return Result.success("删除业主信息成功！");
	}
	
	@RequestMapping("/checkOk")
	@ResponseBody
	public Result checkOk(Long id){
		ShAccount account=accountService.queryAccountById(id);
		//设置用户审核通过状态
		account.setStatus(AccountStatus.NORMAL.getType());
		accountService.edit(account);
		return Result.success("审核成功！用户通过审核！");
	}
	
	@RequestMapping("/accountStatus")
	@ResponseBody
	public List<Combobox> getStatusCombobox(){
		List<Combobox> res=new ArrayList<Combobox>();
		for(int i=0;i<6;i++){
			AccountStatus status=AccountStatus.getByType(i);
			Combobox combo=new Combobox(status.getType()+"",status.getAccountStatus());
			res.add(combo);
		}
		return res;
	}
	
	@SuppressWarnings("unused")
	private boolean saveFile(HttpServletRequest request,ShAccount account,MultipartFile head){
		
		if(account.getId()==null)account.setHeadImage("head_default.jpg");
		if(head==null||head.getSize()==0L){return false;}
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
		try{
			File mm=null;
			if(head!=null){
				String myFileName = head.getOriginalFilename(); 
				if(myFileName.trim()=="")return false;
				String namesss = sdf.format(new Date());
                //重命名上传后的文件名  
                String fileName = "head"+namesss+"."+myFileName.substring(myFileName.lastIndexOf(".")+1);
                String realPath = request.getSession().getServletContext().getRealPath("/");
                String savePath=File.separator+"upload"+File.separator+"account"+File.separator;
                mm=new File(realPath+savePath+fileName);
                head.transferTo(mm);
                account.setHeadImage(fileName);
                return true;
			}
			
		}catch(Exception e){
			return false;
		}
		return false;
	}
	/**
	 * 设置权限
	 */
	private void setAuth(HttpServletRequest request){
		boolean isAdmin = UserHolder.isSuperResidence();
		request.setAttribute("isAdmin", isAdmin);
		if(!isAdmin){
			Long residenceId = UserHolder.getCurrentResidenceId();
			request.setAttribute("residenceId", residenceId);
		}
	}
}
